const { SuccessModel, ErrorModel } = require('../model/resModel');
const { getList, getDetail, add, updateBlog, delBlog } = require('../controller/blog');

const handleBlogRouter = async (req, res) => {
    const { query, body, method, url } = req;
    const path = url.split('?')[0];
    const { id } = query

    if (method === 'POST' && path === '/api/blogs/add') {
        const data = await add(body);
        return new SuccessModel(data, "添加博客成功");
    }

    if (method === 'GET' && path === '/api/blogs/del') {
        const res = await delBlog(id);
        if (res) {
            return new SuccessModel(true, "删除博客成功");
        } else {
            return new ErrorModel(false, "删除博客失败");
        }
    }

    if (method === 'POST' && path === '/api/blogs/update') {
        if (!id) {
            return new ErrorModel("博客id不能为空");
        }
        const res = await updateBlog(id, body);
        if (res) {
            return new SuccessModel(res, "更新博客成功");
        } else {
            return new ErrorModel(res, "更新博客失败");
        }
    }

    if (method === 'GET' && path === '/api/blogs/list') {
        const data = await getList(query.author, query.keyword);
        return new SuccessModel(data, "获取博客列表成功");
    }

    if (method === 'GET' && path === '/api/blogs/detail') {
        const data = await getDetail(query.id);
        if (data) {
            return new SuccessModel(data, "获取博客详情成功");
        } else {
            return new ErrorModel(null, "博客不存在");
        }
    }
}

module.exports = handleBlogRouter;
